package com.controller;

import com.entity.Constants;
import com.entity.Head;
import com.entity.ResultVO;
import com.service.FileUtilService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * ClassName: FileUtilController
 * Package: com.controller
 *
 * @author: guanzepeng
 * @Date: 2021/4/30 16:13 星期五
 * @Description: 图片上传controller
 */
@RestController
@Slf4j
public class FileUtilController {

	@Value("${filePath}")
	private String filePath;

	@Autowired
	private FileUtilService fileUtilService;

		/**
	 * 处理上传图片
	 * @param file 传入图片
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/doUpload",method = RequestMethod.POST)
	public ResultVO uploadImg(
			// 定义一个 MultipartFile 类型的参数 file
			@RequestParam("pclogo") MultipartFile file, Model model) {
		// 如果图片为空,返回false
		if ((file.getOriginalFilename().isEmpty())) {
			log.info("图片为空!");
			return new ResultVO(Constants.OPER_FAILURE,"图片不能为空",null);
		} else {
			Head head = new Head();
			// 获取图片的名字
			String fileName = file.getOriginalFilename();
			try {
				// 图片上传的工具类
				// 参数一：图片的编码格式的字节数组
				// 参数二：图片存放的文件夹地址
				// 参数三：图片的名字
				log.info("图片路径为: {}",filePath);
				log.info("图片名称为: {}",fileName);
				//开始上传
				fileUtilService.uploadFile(file.getBytes(), filePath, fileName);
			} catch (Exception e) {
				e.printStackTrace();
				return new ResultVO(Constants.OPER_FAILURE,"图片上传失败!",null);
			}
		}
		return new ResultVO(Constants.OPER_SUCCESS, "上传成功!", null);
	}
}
